import React, { useState, useEffect } from 'react';
import { 
  Modal, 
  Button, 
  Space, 
  Typography, 
  Card,
  Row,
  Col,
  message,
  Slider,
  Switch,
  Select
} from 'antd';
import {
  ExperimentOutlined,
  SettingOutlined,
  SaveOutlined,
  StarOutlined,
  BulbOutlined,
  RocketOutlined,
  ThunderboltOutlined
} from '@ant-design/icons';

import GraphVisualizationHub from '../../../../components/GraphVisualizationHub';

const { Text, Title } = Typography;
const { Option } = Select;

// 布局算法定义 - 按类别分组
const LAYOUT_CATEGORIES = {
  classic: {
    name: '经典布局',
    description: '满足基础需求的成熟布局算法',
    icon: <StarOutlined />,
    layouts: {
      force: {
        name: '力导向布局',
        description: '基于物理模拟的节点自然分布',
        icon: <ThunderboltOutlined />,
        parameters: {
          nodeStrength: { name: '节点斥力系数', min: 0.1, max: 2.0, default: 0.8, step: 0.1 },
          linkStrength: { name: '关系引力系数', min: 0.1, max: 2.0, default: 0.6, step: 0.1 },
          iterations: { name: '迭代次数', min: 50, max: 500, default: 200, step: 10 },
          centerForce: { name: '中心引力', min: 0, max: 1, default: 0.1, step: 0.05 }
        }
      },
      circular: {
        name: '环形布局',
        description: '节点均匀分布在圆周上',
        icon: <div style={{ width: 14, height: 14, border: '2px solid currentColor', borderRadius: '50%' }} />,
        parameters: {
          radius: { name: '圆环半径', min: 100, max: 500, default: 250, step: 10 },
          startAngle: { name: '起始角度', min: 0, max: 360, default: 0, step: 15 },
          clockwise: { name: '顺时针排列', type: 'boolean', default: true }
        }
      },
      tree: {
        name: '树状布局',
        description: '层级分明的树形结构',
        icon: <div style={{ fontSize: '14px' }}>🌳</div>,
        parameters: {
          direction: { name: '展开方向', type: 'select', options: ['TB', 'BT', 'LR', 'RL'], default: 'TB' },
          nodeSpacing: { name: '节点间距', min: 50, max: 300, default: 120, step: 10 },
          levelSpacing: { name: '层级间距', min: 80, max: 400, default: 150, step: 10 }
        }
      },
      radial: {
        name: '辐射布局',
        description: '从中心向外辐射的结构',
        icon: <div style={{ fontSize: '14px' }}>☀️</div>,
        parameters: {
          centerRadius: { name: '中心半径', min: 50, max: 200, default: 100, step: 10 },
          radiusStep: { name: '半径递增', min: 50, max: 200, default: 80, step: 10 },
          maxRadius: { name: '最大半径', min: 200, max: 600, default: 400, step: 20 }
        }
      }
    }
  },
  creative: {
    name: '创意布局',
    description: '玩可视化花样的创新布局',
    icon: <BulbOutlined />,
    layouts: {
      petal: {
        name: '花瓣形布局',
        description: '如花瓣般优雅的节点排列',
        icon: <div style={{ fontSize: '14px' }}>🌸</div>,
        parameters: {
          petalCount: { name: '花瓣数量', min: 3, max: 12, default: 6, step: 1 },
          petalRadius: { name: '花瓣半径', min: 100, max: 400, default: 200, step: 10 },
          centerSize: { name: '中心区域', min: 20, max: 100, default: 50, step: 5 }
        }
      },
      spiral: {
        name: '螺旋形布局',
        description: '螺旋式的动态美感',
        icon: <div style={{ fontSize: '14px' }}>🌀</div>,
        parameters: {
          spiralTightness: { name: '螺旋紧密度', min: 0.1, max: 2.0, default: 0.8, step: 0.1 },
          spiralTurns: { name: '螺旋圈数', min: 1, max: 10, default: 3, step: 0.5 },
          startRadius: { name: '起始半径', min: 10, max: 100, default: 30, step: 5 }
        }
      },
      honeycomb: {
        name: '蜂窝形布局',
        description: '六边形蜂窝状排列',
        icon: <div style={{ fontSize: '14px' }}>🍯</div>,
        parameters: {
          hexSize: { name: '六边形大小', min: 30, max: 100, default: 60, step: 5 },
          spacing: { name: '蜂窝间距', min: 5, max: 30, default: 10, step: 2 },
          layers: { name: '蜂窝层数', min: 2, max: 8, default: 4, step: 1 }
        }
      }
    }
  },
  experimental: {
    name: '实验性布局',
    description: '尝鲜前沿效果的实验布局',
    icon: <RocketOutlined />,
    layouts: {
      force3d: {
        name: '3D力导向布局',
        description: '三维空间的力导向效果',
        icon: <div style={{ fontSize: '14px' }}>🎯</div>,
        parameters: {
          zStrength: { name: 'Z轴力度', min: 0.1, max: 2.0, default: 0.5, step: 0.1 },
          rotationSpeed: { name: '旋转速度', min: 0, max: 5, default: 1, step: 0.2 },
          perspective: { name: '透视强度', min: 500, max: 2000, default: 1000, step: 50 }
        }
      },
      dynamic: {
        name: '动态流布局',
        description: '节点动态流动的布局',
        icon: <div style={{ fontSize: '14px' }}>🌊</div>,
        parameters: {
          flowSpeed: { name: '流动速度', min: 0.1, max: 3.0, default: 1.0, step: 0.1 },
          waveAmplitude: { name: '波动幅度', min: 10, max: 100, default: 30, step: 5 },
          flowDirection: { name: '流动方向', type: 'select', options: ['horizontal', 'vertical', 'circular'], default: 'horizontal' }
        }
      }
    }
  }
};

/**
 * 布局实验室组件
 * 专注于布局选择和参数调试
 */
const LayoutLab = ({
  visible, 
  onCancel, 
  initialData = { nodes: [], edges: [] },
  onApplyLayout
}) => {
  // 核心状态
  const [currentLayout, setCurrentLayout] = useState('force');
  const [layoutParameters, setLayoutParameters] = useState({});
  const [graphNodes, setGraphNodes] = useState([]);
  const [graphEdges, setGraphEdges] = useState([]);

  // 初始化数据
  useEffect(() => {
    if (initialData && initialData.nodes && initialData.nodes.length > 0) {
      setGraphNodes(JSON.parse(JSON.stringify(initialData.nodes || [])));
      setGraphEdges(JSON.parse(JSON.stringify(initialData.edges || [])));
    }
  }, [initialData]);

  // 初始化布局参数
  useEffect(() => {
    const layoutDef = getLayoutDefinition(currentLayout);
    if (layoutDef && layoutDef.parameters) {
      const defaultParams = {};
      Object.entries(layoutDef.parameters).forEach(([key, param]) => {
        defaultParams[key] = param.default;
      });
      setLayoutParameters(defaultParams);
    }
  }, [currentLayout]);

  // 获取布局定义
  const getLayoutDefinition = (layoutKey) => {
    for (const category of Object.values(LAYOUT_CATEGORIES)) {
      if (category.layouts[layoutKey]) {
        return category.layouts[layoutKey];
      }
    }
    return null;
  };

  // 获取当前布局分类
  const getCurrentLayoutCategory = () => {
    for (const [categoryKey, category] of Object.entries(LAYOUT_CATEGORIES)) {
      if (category.layouts[currentLayout]) {
        return categoryKey;
      }
    }
    return 'classic';
  };

  // 应用布局
  const handleApplyLayout = () => {
    if (onApplyLayout) {
      onApplyLayout({
        layout: currentLayout,
        parameters: layoutParameters,
        nodes: graphNodes,
        edges: graphEdges
      });
      onCancel();
      message.success(`已应用${getLayoutDefinition(currentLayout)?.name}布局`);
    }
  };

  // 渲染布局选择器
  const renderLayoutSelector = () => (
    <div>
      {Object.entries(LAYOUT_CATEGORIES).map(([categoryKey, category]) => (
        <Card 
          key={categoryKey}
          size="small" 
          title={
            <Space>
              {category.icon}
              <span>{category.name}</span>
              <Text type="secondary" style={{ fontSize: '12px' }}>
                {category.description}
              </Text>
            </Space>
          }
          style={{ marginBottom: 12 }}
        >
          <Row gutter={[8, 8]}>
            {Object.entries(category.layouts).map(([layoutKey, layout]) => (
              <Col key={layoutKey} span={6}>
                <Button
                  type={currentLayout === layoutKey ? 'primary' : 'default'}
                  size="small"
                  block
                  onClick={() => setCurrentLayout(layoutKey)}
                  style={{ 
                    height: 'auto', 
                    padding: '8px',
                    textAlign: 'left'
                  }}
                >
                  <div>
                    <div style={{ marginBottom: 4 }}>
                      <Space>
                        {layout.icon}
                        <Text strong style={{ fontSize: '12px' }}>
                          {layout.name}
                        </Text>
                      </Space>
                    </div>
                    <Text type="secondary" style={{ fontSize: '10px' }}>
                      {layout.description}
                    </Text>
                  </div>
                </Button>
              </Col>
            ))}
          </Row>
        </Card>
      ))}
    </div>
  );

  // 渲染参数调试面板
  const renderParameterPanel = () => {
    const layoutDef = getLayoutDefinition(currentLayout);
    if (!layoutDef || !layoutDef.parameters) return null;

    return (
      <Card 
        size="small" 
        title={
          <Space>
            <SettingOutlined />
            <span>{layoutDef.name} - 参数调试</span>
          </Space>
        }
        style={{ marginTop: 16 }}
      >
        <Row gutter={[16, 12]}>
          {Object.entries(layoutDef.parameters).map(([paramKey, param]) => (
            <Col key={paramKey} span={12}>
              <div style={{ marginBottom: 8 }}>
                <Text strong style={{ fontSize: '12px' }}>
                  {param.name}
                </Text>
              </div>
              {param.type === 'boolean' ? (
                <Switch
                  checked={layoutParameters[paramKey]}
                  onChange={(checked) => 
                    setLayoutParameters(prev => ({ ...prev, [paramKey]: checked }))
                  }
                />
              ) : param.type === 'select' ? (
                <Select
                  value={layoutParameters[paramKey]}
                  onChange={(value) => 
                    setLayoutParameters(prev => ({ ...prev, [paramKey]: value }))
                  }
                  size="small"
                  style={{ width: '100%' }}
                >
                  {param.options.map(option => (
                    <Option key={option} value={option}>{option}</Option>
                  ))}
                </Select>
              ) : (
                <Slider
                  min={param.min}
                  max={param.max}
                  step={param.step}
                  value={layoutParameters[paramKey]}
                  onChange={(value) => 
                    setLayoutParameters(prev => ({ ...prev, [paramKey]: value }))
                  }
                  tooltip={{ formatter: (value) => `${value}` }}
                />
              )}
            </Col>
          ))}
        </Row>
      </Card>
    );
  };

  return (
    <Modal
      title={
        <Space>
          <ExperimentOutlined />
          <span>布局实验室</span>
          <Text type="secondary">- 专注布局选择</Text>
        </Space>
      }
      open={visible}
      onCancel={onCancel}
      width={1200}
      centered={true}
      styles={{ body: { padding: '16px' } }}
      footer={[
        <Button key="cancel" onClick={onCancel}>
          取消
        </Button>,
        <Button 
          key="save" 
          type="primary" 
          icon={<SaveOutlined />} 
          onClick={handleApplyLayout}
        >
          应用布局
        </Button>
      ]}
    >
      <Row gutter={16}>
        {/* 左侧控制面板 */}
        <Col span={8}>
          <Title level={5} style={{ marginBottom: 12 }}>
            <ExperimentOutlined style={{ marginRight: 8 }} />
            布局选择
          </Title>
          {renderLayoutSelector()}
          {renderParameterPanel()}
        </Col>
        
        {/* 右侧可视化区域 */}
        <Col span={16}>
          <div style={{ 
            border: '1px solid #d9d9d9', 
            borderRadius: '6px',
            background: '#fff',
            height: 600,
            position: 'relative'
          }}>
            {/* 可视化组件 */}
            <GraphVisualizationHub
              nodes={graphNodes}
              edges={graphEdges}
              layout={currentLayout}
              layoutParameters={layoutParameters}
              onLayoutChange={setCurrentLayout}
              editable={false} // 布局实验室模式下不可编辑节点
              height={600}
              errorHandler={(error) => {
                console.error("布局渲染错误:", error);
                message.error('布局渲染出现问题');
              }}
            />
            
            {/* 布局信息显示 */}
            <div style={{ 
              position: 'absolute', 
              bottom: 12, 
              left: 12,
              zIndex: 10
            }}>
              <Card size="small" style={{ minWidth: 200 }}>
                <Space direction="vertical" size="small">
                  <div>
                    <Text strong>{getLayoutDefinition(currentLayout)?.name}</Text>
                    <Text type="secondary" style={{ marginLeft: 8, fontSize: '11px' }}>
                      {getCurrentLayoutCategory() === 'classic' ? '经典' : 
                       getCurrentLayoutCategory() === 'creative' ? '创意' : '实验性'}
                    </Text>
                  </div>
                  <div>
                    <Text style={{ fontSize: '12px' }}>
                      节点: {graphNodes.length} | 关系: {graphEdges.length}
                    </Text>
                  </div>
                </Space>
              </Card>
            </div>
          </div>
        </Col>
      </Row>
    </Modal>
  );
};

export default LayoutLab;